package com.fch.server.service;

import com.fch.server.domain.Chapter;
import com.fch.server.domain.ChapterExample;
import com.fch.server.dto.ChapterDto;
import com.fch.server.dto.ChapterPageDto;
import com.fch.server.dto.PageDto;
import com.fch.server.mapper.ChapterMapper;
import com.fch.server.util.CopyUtil;
import com.fch.server.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: fangchuhao
 * @description:
 * @create: 2023-02-27 09:16
 **/
@Service
public class ChapterService {
    private static final Logger LOG = LoggerFactory.getLogger(ChapterService.class);

    @Resource
    private ChapterMapper chapterMapper;

    /**
     * 列表查询
     */
    public void list(ChapterPageDto chapterPageDto) {
        PageHelper.startPage(chapterPageDto.getPage(),chapterPageDto.getSize());
        ChapterExample chapterExample = new ChapterExample();
        ChapterExample.Criteria criteria = chapterExample.createCriteria();
        if (!StringUtils.isEmpty(chapterPageDto.getCourseId())) {
            criteria.andCourseIdEqualTo(chapterPageDto.getCourseId());
        }
        List<Chapter> chapters = chapterMapper.selectByExample(chapterExample);
        PageInfo<Chapter> chapterPageInfo = new PageInfo<>(chapters);
        chapterPageDto.setTotal(chapterPageInfo.getTotal());
        List<ChapterDto> chapterDtos = CopyUtil.copyList(chapters, ChapterDto.class);
        chapterPageDto.setList(chapterDtos);
    }

    /**
     * 保存，id有值时更新，无值时新增
     */
    public void save(ChapterDto chapterDto) {
        Chapter chapter = CopyUtil.copy(chapterDto,Chapter.class);
        if (StringUtils.isEmpty(chapter.getId())) {
            insert(chapter);
        }else {
            update(chapter);
        }
    }

    /**
     * 新增
     */
    private void insert(Chapter chapter) {
        chapter.setId(UuidUtil.getShortUuid());
        chapterMapper.insert(chapter);
    }

    /**
     * 更新
     */
    private void update(Chapter chapter) {
        chapterMapper.updateByPrimaryKey(chapter);
    }

    /**
     * 删除
     */
    public void delete(String id) {
        chapterMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询某一课程下的所有章
     */
    public List<ChapterDto> listByCourse(String courseId) {
        ChapterExample example = new ChapterExample();
        example.createCriteria().andCourseIdEqualTo(courseId);
        List<Chapter> chapters = chapterMapper.selectByExample(example);
        return CopyUtil.copyList(chapters, ChapterDto.class);
    }
}
